<template>
  <Drawer :visible="props.showModal" :closable="false" width="600">
    <template #title>
      <div class="title-header">{{ `${props.title}保藏区` }}</div>
    </template>

    <template #extra><CloseOutlined @click="modalCancelFn" /></template>

    <template #footer>
      <div style="display: flex; justify-content: center">
        <Button style="margin-right: 50px" @click="modalCancelFn">取消</Button>
        <Button type="primary" @click="modalOkFn">保存</Button>
      </div>
    </template>

    <Form ref="formRef" :model="state.data" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="保藏区名称" name="name">
        <Input v-model:value="state.data.name" />
      </a-form-item>

      <a-form-item label="保藏区图片" name="image">
        <div style="display: flex">
          <Upload :show-upload-list="false" :beforeUpload="beforeUpload" :custom-request="customRequestFn">
            <div class="upload-img-box">
              <img v-if="state.imgURL" :src="state.imgURL" alt="" />
              <PlusOutlined v-else style="font-size: 30px; color: #8b8b9e" />
            </div>
          </Upload>
          <div style="margin: 10px; color: red">{{ '格式要求：jpg、png，<200k' }}</div>
        </div>
      </a-form-item>

      <a-form-item label="保藏区编号" name="serial">
        <Input :disabled="props.title === '修改'" v-model:value="state.data.serial" />
      </a-form-item>
    </Form>
  </Drawer>
</template>

<script setup lang="ts">
import { message, Form, Input, Upload, Drawer } from 'ant-design-vue';
import { reactive, ref, watch } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { uploadFile } from '@/api/public';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { addStorage, getStorage, putStorage } from '@/modules/underlying-data/api/storage-managment';

/**
 * const
 */
const props = withDefaults(
  defineProps<{
    showModal?: boolean;
    data: any;
    title: string;
  }>(),
  {
    showModal: false,
  },
);
watch(
  () => props.showModal,
  async () => {
    if (props.showModal) {
      if (props.title === '修改') {
        const res = await getStorage(props.data?.storageId);
        state.data = res.result;
      } else {
        state.data = props.data;
      }
      state.imgURL = props.data?.url;
    }
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'editModalOk'): void;
}>();
const formRef = ref();

/**
 * data
 */
const state: {
  data: any;
  imgURL: any;
  showUploadLoading: boolean;
} = reactive({
  data: {},
  imgURL: '',
  showUploadLoading: false,
});
const rules = {
  name: [{ required: true, message: '数据必填!' }],
  image: [{ required: true, message: '数据必填!' }],
  serial: [{ required: true, message: '数据必填!' }],
};
/**
 * fn
 */
const modalOkFn = async () => {
  try {
    await formRef.value?.validateFields();
  } catch {
    return;
  }
  let params: any = {
    desp: state.data?.desp,
    name: state.data?.name,
    serial: state.data?.serial,
    image: state.data?.image,
  };
  if (props.title === '新增') {
    params.type = 1;
    await addStorage(params);
  } else {
    params.id = props.data?.storageId;
    await putStorage(params);
  }
  message.success('操作成功！');
  emits('editModalOk');
  modalCancelFn();
};
const modalCancelFn = () => {
  formRef.value?.resetFields();
  state.data = {};
  state.imgURL = '';
  emits('update:showModal', false);
};

/**
 * upload
 */
const customRequestFn = async (e) => {
  state.showUploadLoading = true;
  const reader = new FileReader();
  reader.readAsDataURL(e.file);
  reader.addEventListener('load', () => {
    state.imgURL = reader.result;
  });
  const formData = new FormData();
  formData.append('file', e.file);
  const res = await uploadFile(formData);
  state.data.image = res.result.md5;
  e.onSuccess();
  state.showUploadLoading = false;
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('仅允许jpg、png格式图片!');
  }
  const isLt200K = file.size / 1024 < 200;
  if (!isLt200K) {
    message.error('文件大小应小于200k!');
  }
  return isJpgOrPng && isLt200K;
};
</script>

<style scoped lang="less">
.upload-img-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 105px;
  height: 114px;
  border: 1px solid #cecece;
  > img {
    object-fit: contain;
  }
}
</style>
